package org.streets.eis.component.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.inmethod.grid.IDataSource;

/**
 * 不支持分页和过滤
 */
public class MemoryTableModel<T extends Serializable> implements IDataSource {
	private static final long serialVersionUID = 1L;

	private List<T> rows = new ArrayList<T>();
	
	public MemoryTableModel(){		
	}
	
	public MemoryTableModel(List<T> items) {
		if (items!=null) {
			this.rows.addAll(items);
		}
	}
	
	@SuppressWarnings("unchecked")
	public IModel model(Object object) {
		return new Model<T>((T)object);
	}
	
	public void query(IQuery query, IQueryResult result) {		
		result.setTotalCount(rows.size());		
		result.setItems(rows.iterator());	
	}
	
	public void detach() {
	}
	
	public int getRowCount(){
		return rows.size();
	}
	
	public MemoryTableModel<T> addRow(T row){
		rows.add(row);
		return this;
	}
	
	public MemoryTableModel<T> addRow(int index,T row){
		rows.add(index,row);
		return this;
	}	
	
	public MemoryTableModel<T> removeRow(T row){
		rows.remove(row);
		return this;
	}

	public MemoryTableModel<T> removeRow(int index){
		rows.remove(index);
		return this;
	}		
	
	public T getRowAt(int index){
		return rows.get(index);
	}	
	
	public T findRow(T item){
		T o = null;
		if (item == null) {
		    for (int i = 0; i < rows.size(); i++){
		    	o = rows.get(i);
		    	if (o==null) break;
		    }
		} else {
		    for (int i = 0; i < rows.size(); i++){
		    	o = rows.get(i);
		    	if (item.equals(o)) break;
		    }
		}
		return o;
	}	
	
	public int indexOf(T item){
		return rows.indexOf(item);
	}	
	
	public Iterator<T> iterator(){
		return rows.iterator();
	}
	
	public MemoryTableModel<T> clear(){
		rows.clear();
		return this;
	}	
	
}
